<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" label-width="80px">
      <el-form-item label="标题" prop="bannerTitle">
        <el-input v-model="queryParams.bannerTitle" placeholder="请输入标题" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="list.slice((pageNum-1)*pageSize,pageNum*pageSize)" style="width: 100%;">
      <el-table-column label="序号" type="index" align="center">
        <template slot-scope="scope">
          <span>{{ (pageNum - 1) * pageSize + scope.$index + 1 }}</span>
        </template>
      </el-table-column>
      <el-table-column label="标题" align="center" prop="bannerTitle"/>
      <el-table-column label="描述" align="center" prop="bannerRemark"/>
      <el-table-column label="按钮标题" align="center" prop="buttonTitle"/>
      <el-table-column label="跳转URL" align="center" prop="buttonTargetUrl"/>
      <el-table-column label="排序号" align="center" prop="sortNum"/>
      <el-table-column label="更新时间" align="center" prop="updateTime" width="180"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="pageNum" :limit.sync="pageSize"/>

    <!-- 添加或修改对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="标题" prop="bannerTitle">
          <el-input v-model="form.bannerTitle" placeholder="请输入标题"/>
        </el-form-item>
        <el-form-item label="描述" prop="bannerRemark">
          <el-input type="textarea" :rows="3" v-model="form.bannerRemark" placeholder="请输入描述"/>
        </el-form-item>
        <el-form-item label="图片" prop="fileId">
          <el-upload
            :action="uploadAction"
            list-type="picture-card"
            :limit="1"
            :file-list="uploadFileList"
            :headers="uploadHeaders"
            :on-success="onUploadSuccess"
            :on-remove="onUploadRemove"
            :on-error="onUploadError"
            :before-upload="onBeforeUpload"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
          <div class="el-upload__tip" slot="tip">仅支持图片文件，大小≤5MB</div>
        </el-form-item>
        <el-form-item label="按钮标题" prop="buttonTitle">
          <el-input v-model="form.buttonTitle" placeholder="请输入按钮标题"/>
        </el-form-item>
        <el-form-item label="跳转URL" prop="buttonTargetUrl">
          <el-input v-model="form.buttonTargetUrl" placeholder="请输入跳转URL"/>
        </el-form-item>
        <el-form-item label="排序号" prop="sortNum">
          <el-input-number v-model="form.sortNum" controls-position="right" :min="0" :max="99999999" placeholder="越大越靠前"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
  </template>

<script>

import { listBanner, saveBanner, delBanner } from "@/api/official/banner"
import { viewFile } from "@/api/system/file"
import { getToken } from "@/utils/auth"

export default {
  name: "Banner",
  data() {
    return {
      loading: true,
      total: 0,
      list: [],
      showSearch: true,
      pageNum: 1,
      pageSize: 10,
      open: false,
      title: "",
      form: {},
      uploadAction: process.env.VUE_APP_BASE_API + '/system/file/upload',
      uploadHeaders: { Authorization: 'Bearer ' + getToken() },
      uploadFileList: [],
      queryParams: {
        bannerTitle: undefined
      },
      rules: {
        bannerTitle: [ { required: true, message: "标题不能为空", trigger: "blur" } ],
        bannerRemark: [ { required: true, message: "描述不能为空", trigger: "blur" } ],
        fileId: [ { required: true, message: "必须上传图片", trigger: "blur" } ],
        buttonTitle: [ { required: true, message: "按钮标题不能为空", trigger: "blur" } ],
        buttonTargetUrl: [ { required: true, message: "跳转URL不能为空", trigger: "blur" } ],
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.loading = true
      listBanner(this.queryParams).then(response => {
        this.list = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    reset() {
      this.form = {
        id: undefined,
        bannerTitle: undefined,
        bannerRemark: undefined,
        fileId: undefined,
        buttonTitle: undefined,
        buttonTargetUrl: undefined,
        sortNum: 0
      }
      this.resetForm("form")
      this.uploadFileList = []
    },
    handleQuery() {
      this.pageNum = 1
      this.getList()
    },
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    handleAdd() {
      this.reset()
      this.title = "添加Banner"
      this.open = true
    },
    handleEdit(row) {
      this.reset()
      this.title = "编辑Banner"
      this.form = JSON.parse(JSON.stringify(row))
      this.open = true
      // 预填已上传图片预览
      if (this.form.fileId) {
        viewFile(this.form.fileId).then(res => {
          if (res && res.data) {
            this.uploadFileList = [{
              name: res.data.originalName || res.data.fileName || 'image',
              url: res.data.fullPath,
              uid: res.data.id
            }]
          }
        }).catch(() => {})
      }
    },
    handleDelete(row) {
      this.$modal.confirm('是否确认删除标题为"' + row.bannerTitle + '"的数据项？').then(() => {
        return delBanner(row.id)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    cancel() {
      this.open = false
      this.reset()
    },
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          const payload = {
            id: this.form.id || '',
            bannerTitle: this.form.bannerTitle,
            bannerRemark: this.form.bannerRemark,
            fileId: this.form.fileId,
            buttonTitle: this.form.buttonTitle,
            buttonTargetUrl: this.form.buttonTargetUrl,
            sortNum: this.form.sortNum
          }
          saveBanner(payload).then(() => {
            if (this.form.id != undefined && this.form.id !== '') {
              this.$modal.msgSuccess("修改成功")
            } else {
              this.$modal.msgSuccess("新增成功")
            }
            this.open = false
            this.getList()
            this.reset()
          }).catch(err => {
            console.error('saveBanner error:', err)
            this.$modal.msgError(err && err.message ? err.message : '保存失败')
          })
        }
      })
    },
    onBeforeUpload(file) {
      const isImage = file.type.startsWith('image/')
      const isLt5M = file.size / 1024 / 1024 < 5
      if (!isImage) this.$modal.msgError('仅支持图片文件')
      if (!isLt5M) this.$modal.msgError('图片大小不能超过5MB')
      return isImage && isLt5M
    },
    onUploadSuccess(res) {
      if (res && res.code === 200 && res.data) {
        this.form.fileId = res.data.id
        // 规范化 fileList（el-upload 会自动追加当前文件到列表）
      } else {
        this.$modal.msgError(res && res.msg ? res.msg : '上传失败')
      }
    },
    onUploadError() {
      this.$modal.msgError('上传失败，请重试')
    },
    onUploadRemove() {
      this.form.fileId = undefined
    }
  }
}

</script>

<style scoped>
</style>
